﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ApplicationBarMVVMApp.MVVM
{
    public class RelayCommand : IRelayCommand
    {
        #region Fields

        private readonly Action _execute;
        private readonly Func<bool> _canExecute;

        #endregion Fields

        #region Constructors

        public RelayCommand(Action execute)
            : this(execute, null)
        {
        }

        public RelayCommand(Action execute, Func<bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        #endregion Constructors

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            return null == _canExecute ? true : _canExecute();
        }

        public void Execute(object parameter)
        {
            _execute();
        }

        public void RaiseCanExecuteChanged()
        {
            if (null != this.CanExecuteChanged)
                this.CanExecuteChanged.Invoke(this, EventArgs.Empty);
        }

        public event EventHandler CanExecuteChanged;

        #endregion ICommand Members
    }

    public class RelayCommand<T> : IRelayCommand
    {
        #region Fields

        private readonly Action<T> _execute;
        private readonly Func<T, bool> _canExecute;

        #endregion Fields

        #region Constructors

        public RelayCommand(Action<T> execute)
            : this(execute, null)
        {
        }

        public RelayCommand(Action<T> execute, Func<T, bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        #endregion Constructors

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            parameter = null == parameter ? default(T) : parameter;
            return null == _canExecute ? true : _canExecute((T)parameter);
        }

        public void Execute(object parameter)
        {
            parameter = null == parameter ? default(T) : parameter;
            _execute((T)parameter);
        }

        public void RaiseCanExecuteChanged()
        {
            if (null != this.CanExecuteChanged)
                this.CanExecuteChanged.Invoke(this, EventArgs.Empty);
        }

        public event EventHandler CanExecuteChanged;

        #endregion ICommand Members
    }
}
